# -*- encoding:utf8 -*-
from django.utils import timezone
from django.db.models.signals import pre_save,post_save,pre_delete
from django.dispatch import receiver,Signal
from leave_application.check import get_or_create_application_check_record,compute_application_status,notify_next_check_person
from attendance.models import ConsumeRelation,LeaveApplication,AvaiLeave
from attendance.tool_func import get_or_none
from attendance.convert import i2t,t2i
from leave_application.leave_apply import match,post_application
from annual import annual_accum

leave_app_switch_approved=Signal(providing_args=["instance"])


@receiver(pre_save,sender=LeaveApplication,dispatch_uid="pre_application_save")
def pre_application_save(sender,instance,**kw):
    """
    [1]当状态变为revoked时，删除所有的LeaveModel
    ToDo:更改LeaveApplication.usedleave的名字
    
    [2]保存前，自动更新领导列表；根据领导审批情况，更新整条假期申请的状态。
    @instance:LeaveApplication的对象

    """
    #[1]
    old= get_or_none(sender,id=instance.id)
    if old and old.status!=instance.status:
        if instance.status in ['revoked','rejected']:
            instance.usedleave.all().delete()
  
    # [2]
    leaders=get_or_create_application_check_record(instance)  
    status=compute_application_status(leaders)
    if instance.status !='revoked' and status!=instance.status:
        instance.status=status


    
@receiver(post_save,sender=LeaveApplication,dispatch_uid="post_application_save")
def post_application_save(sender,instance,**kw):
    """
    保存后，发送通知给下一位审批领导
    """
    # [1] 投递到 LeaveModel
    if instance.usedleave.all().count()==0 and instance.status not in ['revoked','rejected']:
        post_application(instance)
    
    # [2] 通知应该通知的领导
    notify_next_check_person(instance) 
    
    # [3] 新的假期申请状态，在approved相关切换时，需要更新考勤
    if instance.org_status!=instance.status and (instance.org_status=='approved' or instance.status=='approved'):
        leave_app_switch_approved.send(sender=LeaveApplication,instance=instance)  
    
    # 还原hook状态
    instance.org_status=instance.status
 
 
@receiver(pre_delete,sender=ConsumeRelation)
def post_relation_deleted(sender,instance,**kw):
    """当关系被删除时，将该关系所占用的长度还给avai_leave
    @type instance:ConsumeRelation ,ConsumeRelation的对象
    
    """
    used = t2i(instance.avai_leave.used)
    instance.avai_leave.used= i2t(used-instance.span())
    instance.avai_leave.save()




# @receiver(read_avai_leave)
# def update_annual(sender,instance,**kw):
    # """更新今年的累积年假
    # """
    # if instance.category=='annual_leave':
        # now=timezone.now().date()
        # thisyear_str = '%s-01-01' % now.year
        # if instance.start_date==thisyear_str:
            # span = annual_accum(instance.staff)
            # instance.span=i2t(span)
            # instance.save()
            # # 因为年假可以透支0.5天，所以要在年假够了的情况下，match掉透支的年假
            
            # match(instance.staff)
